package com.example.dps;

import java.util.Date;

import com.loopj.android.http.PersistentCookieStore;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.RingtoneManager;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;



public class AlarmReceiver extends BroadcastReceiver {
	
	String tag = "AlarmReceiver";
	
	AddMoneyService service;
	
	Context context;
	Intent intent;
	
	TransferDBHelper transferDBHelper;
	DBHelper dbHelper;
	AccountDBHelper accountDBHelper;
	WebHelper webHelper;
	
	/** is the alarm for a transfer? or notification **/
	boolean isTransfer = false;
	
	/** is the alarm removing a cookie? **/
	boolean removeCookie = false;

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		Toast.makeText(context, "Received alarm broadcast", Toast.LENGTH_LONG).show();
		
		
		this.context = context;
		this.intent = intent;
		
		isTransfer = intent.getExtras().getBoolean("isTransfer");
				//..getBooleanExtra("isTransfer", false);
		
		removeCookie = intent.getExtras().getBoolean("removeCookie");
		
		
		this.transferDBHelper = new TransferDBHelper(context);
		this.dbHelper = new DBHelper(context);
		this.accountDBHelper = new AccountDBHelper(context);
		this.service = new AddMoneyService();
		this.webHelper = new WebHelper(context);
		
		
		if(removeCookie){
			Log.e(tag, "removeCookie = true");
			removeCookie();
		}
		else if(isTransfer){
			Log.e("AlarmReceiver", "isTranfer = True");
			alertTransfer();
		}
		else{
			Log.e(tag, "isTransfer = false");
			
			alertReminder();
		}

		
	}
	
	public void alertReminder(){
		
		
		Date now = new Date();
		Date lastDeposit = this.dbHelper.getLastDeposit();
		
		int daysSinceDeposit = 0;
		if(lastDeposit == null){
			Log.e(tag, "lastDeposit == null!!!!");
			daysSinceDeposit = -1;
		}
		else{
			daysSinceDeposit = (int) ((now.getTime() - lastDeposit.getTime())/(1000*60*60*24));
		}
		
		createReminder(daysSinceDeposit);
		
	}
	
	

	public void alertTransfer(){
		
		/** perform the actual transfer **/
		int transferID = this.intent.getExtras().getInt("transferID");
		Log.e(tag, "Startings TransferID = " + transferID);
		Transfer transfer= transferDBHelper.getTransferFromID(transferID);
		

		
		boolean completedTransfer = false;
		
		
		
		if(transferID <=0) new Throwable("transfer ID does not exist!");
		else if(transfer.enabled){
			completedTransfer = performTransfer(transferID);
		}
		else if(transfer.enabled == false){
			//update next transfer but don't perform transaction
			Log.e(tag, "transer is disabled");
		}
		
		if(transfer.enabled && completedTransfer){
			/**transfer success, notify user **/
			
			this.webHelper.updateAccountInfo();
			
			
			NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
			
			Intent notificationIntent = new Intent(context, TabRoot.class);
			notificationIntent.putExtra("START_TAB", "view_savings");
			PendingIntent contentIntent = PendingIntent.getActivity(context,
			        transfer.id, notificationIntent,
			        PendingIntent.FLAG_CANCEL_CURRENT);

			Intent intent = new Intent(context, AddMoneyActivity.class);
			
			builder.setContentIntent(contentIntent)
			    .setSmallIcon(R.drawable.ic_launcher)
			    .setTicker("Performed Automatic Transfer!")
			    .setAutoCancel(true)
			    .setContentTitle("Added Automatic Transfer")
			    .setContentText("Down Payment Saver has performed an automatic transfer into your savings account");

			
			
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.context);
			
			/**if vibrate enabled, play vibrate **/
			if(prefs.getBoolean("enableVibratePref", true)){
				builder.setVibrate(new long[] { 500, 500 });
			}
			if(prefs.getBoolean("enableSoundPref" , false)) {
				//Define sound URI
				builder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
			}
			
			Notification notification = builder.getNotification();
			
			NotificationManager nm = (NotificationManager) context
			        .getSystemService(Context.NOTIFICATION_SERVICE);
			
			nm.notify(R.string.app_name, notification);
		}
		else if(transfer.enabled && completedTransfer == false){
			/** transfer failed, notify user **/
			
			NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
			
			Intent notificationIntent = new Intent(context, TabRoot.class);
			notificationIntent.putExtra("START_TAB", "view_savings");
			PendingIntent contentIntent = PendingIntent.getActivity(context,
			        transfer.id, notificationIntent,
			        PendingIntent.FLAG_CANCEL_CURRENT);

			Intent intent = new Intent(context, AddMoneyActivity.class);
			
			builder.setContentIntent(contentIntent)
			    .setSmallIcon(R.drawable.ic_launcher)
			    .setTicker("Automatic Transfer Failed!")
			    .setAutoCancel(true)
			    .setContentTitle("Automatic Transfer")
			    .setContentText("Down Payment Saver was unable to perform an automatic transfer into your savings account. You may not have had enough money in your account");
			
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.context);
			
			/**if vibrate enabled, play vibrate **/
			if(prefs.getBoolean("enableVibratePref", true)){
				builder.setVibrate(new long[] { 500, 500 });
			}
			if(prefs.getBoolean("enableSoundPref" , false)) {
				//Define sound URI
				builder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
			}

			Notification notification = builder.getNotification();
			
			NotificationManager nm = (NotificationManager) context
			        .getSystemService(Context.NOTIFICATION_SERVICE);
			
			nm.notify(R.string.app_name, notification);
		}
		else if(transfer.enabled == false){
			/** do nothing, transfer was not enabled **/
		}
		
		
		
		
	}
	public boolean performTransfer(int transferID) {
		
		/** perform the given transfer **/
		Log.e(tag, "performing scheduled transfer! on transferID = " + transferID);
		
		Transfer transfer = transferDBHelper.getTransferFromID(transferID);
		
		Log.e(tag, "performTransfer: transfar.id = " +transfer.id+ " transferID == " + transferID);
		
		transfer.lastTransfer = new Date();
		transfer.updateNextTransfer();
		Log.e(tag, "performTransfer new next transfer ==== " + transfer.nextTransfer.toLocaleString());
		this.transferDBHelper.updateTransfer(transfer);
		
		if(this.accountDBHelper.transferMoney(transfer.from, transfer.to, transfer.amount)){
			//update last deposit
			this.dbHelper.setLastDeposit();
			this.transferDBHelper.updateTransfer(transfer);
			return true;
		}
		else {
			this.dbHelper.setLastDeposit();
			this.transferDBHelper.updateTransfer(transfer);
			return false;
		}
		
		
		
	}
	
	public void createReminder(int daysSinceDeposit){
		
		Log.e(tag, "ALERTING REMINDER***");
		
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.context);
		
		NotificationCompat.Builder builder = new NotificationCompat.Builder(this.context);
		
		Intent notificationIntent = new Intent(this.context, TabRoot.class);
		notificationIntent.putExtra("START_TAB", "add_money");
		PendingIntent contentIntent = PendingIntent.getActivity(this.context,
		        0, notificationIntent,
		        PendingIntent.FLAG_CANCEL_CURRENT);
		
		

		Intent intent = new Intent(this.context, AddMoneyActivity.class);
		
		builder.setContentIntent(contentIntent)
		    .setSmallIcon(R.drawable.ic_launcher)
		    .setTicker("Time to add more to Down Payment")
		    .setAutoCancel(true)
		    .setContentTitle("Down Payment Deposit Reminder")
		    .setContentText("It has been " + daysSinceDeposit + " days since your last deposit")
			.setSmallIcon(R.drawable.header_home_icon);
		
		
		
		/**if vibrate enabled, play vibrate **/
		if(prefs.getBoolean("enableVibratePref", true)){
			builder.setVibrate(new long[] { 500, 500 });
		}
		if(prefs.getBoolean("enableSoundPref" , false)) {
			//Define sound URI
			builder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
		}

		Notification notification = builder.getNotification();
		
		NotificationManager nm = (NotificationManager) this.context
		        .getSystemService(Context.NOTIFICATION_SERVICE);
		
		nm.notify(R.string.app_name, notification);
		
		this.dbHelper.setLastReminded();
		
	}
	
	/** removes the cookie and effectively logs out the user **/
	public void removeCookie(){
		
		//TODO
		//PersistentCookieStore cookieStore = new PersistentCookieStore(this.activity);
		
		
	}

}
